<template>
  <div class="question-list-container">
    <div class="question-list-header">
      <h2>问题列表</h2>
      
      <div class="filter-bar">
        <el-select v-model="categoryId" clearable placeholder="选择分类" @change="handleFilterChange">
          <el-option
            v-for="item in categories"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        
        <el-input
          v-model="keyword"
          placeholder="搜索问题..."
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
          @clear="handleSearch"
        >
          <template #suffix>
            <el-icon class="el-input__icon" @click="handleSearch">
              <el-icon-search />
            </el-icon>
          </template>
        </el-input>
        
        <div class="tabs">
          <el-radio-group v-model="activeTab" @change="handleTabChange">
            <el-radio-button label="all">全部问题</el-radio-button>
            <el-radio-button label="hot">热门问题</el-radio-button>
            <el-radio-button label="waiting">等待回答</el-radio-button>
          </el-radio-group>
        </div>
      </div>
    </div>
    
    <div class="question-list">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <el-skeleton :rows="5" animated />
        <div class="loading-text">正在加载问题列表...</div>
      </div>
      
      <!-- 空状态 -->
      <el-empty 
        v-else-if="questionList.length === 0" 
        description="暂无相关问题"
      >
        <template #description>
          <p>当前没有符合条件的问题</p>
        </template>
        <el-button type="primary" @click="resetFilters">清除筛选条件</el-button>
      </el-empty>
      
      <!-- 问题列表 -->
      <div v-else class="question-items">
        <transition-group name="question-fade">
          <div 
            v-for="question in questionList" 
            :key="question.id" 
            class="question-item" 
            @click="viewQuestion(question.id)"
          >
            <div class="stats">
              <div class="stat">
                <strong>{{ question.viewCount || 0 }}</strong>
                <span>浏览</span>
              </div>
              <div class="stat">
                <strong>{{ question.answerCount || 0 }}</strong>
                <span>回答</span>
              </div>
            </div>
            
            <div class="content">
              <h3 class="title">{{ question.title }}</h3>
              <p class="excerpt" v-if="question.content">{{ getContentPreview(question.content) }}</p>
              <div class="tags">
                <el-tag v-if="question.categoryName" size="small" type="info">{{ question.categoryName }}</el-tag>
                <el-tag 
                  v-for="(tag, index) in question.tags ? question.tags.split(',').filter(t => t.trim()) : []" 
                  :key="index" 
                  size="small" 
                  class="tag"
                >
                  {{ tag }}
                </el-tag>
              </div>
              <div class="meta">
                <div class="user-info">
                  <el-avatar :size="24" :src="question.avatar || defaultAvatar"></el-avatar>
                  <span class="username">{{ question.nickname || '匿名用户' }}</span>
                  <el-tag v-if="question.isExpert" size="small" type="warning">专家</el-tag>
                </div>
                <span class="time">{{ formatDate(question.createTime) }}</span>
              </div>
            </div>
            
            <div class="status">
              <el-tag v-if="question.status === 0" type="info">待审核</el-tag>
              <el-tag v-else-if="question.status === 1" type="primary">进行中</el-tag>
              <el-tag v-else-if="question.status === 2" type="success">已解决</el-tag>
              <el-tag v-else-if="question.status === 3" type="warning">已关闭</el-tag>
            </div>
          </div>
        </transition-group>
      </div>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getQuestionList, getHotQuestions, getWaitingQuestions } from '../api/question';
import { getAllCategories } from '../api/category';

const router = useRouter();
const questionList = ref([]);
const categories = ref([]);
const total = ref(0);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const categoryId = ref('');
const keyword = ref('');
const activeTab = ref('all');
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

// 获取问题列表
const fetchQuestionList = async () => {
  try {
    loading.value = true;
    
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      categoryId: categoryId.value || undefined,
      keyword: keyword.value || undefined
    };
    
    let res;
    if (activeTab.value === 'hot') {
      res = await getHotQuestions(params);
    } else if (activeTab.value === 'waiting') {
      res = await getWaitingQuestions(params);
    } else {
      res = await getQuestionList(params);
    }
    
    questionList.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {
    console.error('获取问题列表失败:', error);
    ElMessage.error('获取问题列表失败');
  } finally {
    // 延迟关闭加载状态，提供更好的视觉效果
    setTimeout(() => {
      loading.value = false;
    }, 300);
  }
};

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await getAllCategories();
    categories.value = res.data;
  } catch (error) {
    console.error('获取分类列表失败:', error);
  }
};

// 获取内容预览
const getContentPreview = (content) => {
  // 去除HTML标签和多余空格
  const plainText = content.replace(/<[^>]+>/g, '').replace(/\s+/g, ' ').trim();
  // 截取前100个字符
  return plainText.length > 100 ? plainText.substring(0, 100) + '...' : plainText;
};

// 重置筛选条件
const resetFilters = () => {
  categoryId.value = '';
  keyword.value = '';
  activeTab.value = 'all';
  currentPage.value = 1;
  fetchQuestionList();
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchQuestionList();
};

// 处理过滤条件变化
const handleFilterChange = () => {
  currentPage.value = 1;
  fetchQuestionList();
};

// 处理标签页切换
const handleTabChange = () => {
  currentPage.value = 1;
  fetchQuestionList();
};

// 处理页码变化
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchQuestionList();
};

// 查看问题详情
const viewQuestion = (id) => {
  router.push(`/questions/${id}`);
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const now = new Date();
  const diff = now.getTime() - d.getTime();
  
  // 1分钟内
  if (diff < 60000) {
    return '刚刚';
  }
  
  // 1小时内
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`;
  }
  
  // 24小时内
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`;
  }
  
  // 30天内
  if (diff < 2592000000) {
    return `${Math.floor(diff / 86400000)}天前`;
  }
  
  // 超过30天
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
};

onMounted(() => {
  fetchQuestionList();
  fetchCategories();
});
</script>

<style>
.question-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.question-list-header {
  margin-bottom: 20px;
}

.question-list-header h2 {
  font-size: 24px;
  margin-bottom: 16px;
}

.filter-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.search-input {
  width: 240px;
}

.tabs {
  margin-left: auto;
}

.question-items {
  margin-bottom: 20px;
}

.question-item {
  display: flex;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 16px;
  background-color: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s ease;
}

.question-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.12);
}

.stats {
  display: flex;
  flex-direction: column;
  margin-right: 24px;
  min-width: 80px;
  justify-content: center;
  align-items: center;
}

.stat {
  text-align: center;
  margin-bottom: 8px;
}

.stat strong {
  display: block;
  font-size: 18px;
}

.stat span {
  font-size: 12px;
  color: #666;
}

.content {
  flex: 1;
}

.title {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 10px;
  color: #333;
}

.excerpt {
  font-size: 14px;
  line-height: 1.5;
  margin: 0 0 12px;
  color: #666;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.tags {
  margin-bottom: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.tag {
  margin-right: 6px;
}

.meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
}

.username {
  margin: 0 10px;
  font-size: 14px;
}

.time {
  font-size: 12px;
  color: #8c8c8c;
}

.status {
  margin-left: 16px;
  display: flex;
  align-items: center;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.loading-text {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}

/* 列表动画效果 */
.question-fade-enter-active,
.question-fade-leave-active {
  transition: all 0.5s ease;
}

.question-fade-enter-from {
  opacity: 0;
  transform: translateY(20px);
}

.question-fade-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input {
    width: 100%;
  }
  
  .tabs {
    margin-left: 0;
    margin-top: 10px;
  }
  
  .question-item {
    flex-direction: column;
  }
  
  .stats {
    flex-direction: row;
    justify-content: flex-start;
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .stat {
    margin-right: 20px;
    margin-bottom: 0;
  }
  
  .status {
    margin-left: 0;
    margin-top: 10px;
    justify-content: flex-end;
  }
}
</style> 